<template>
  <q-page class="flex row">
    <!-- 左边区域 -->
    <div class="flex column items-start q-pa-md" style="width: 30%">
      <div class="q-mb-md extended-input">
        <q-input class="extended-input" type="textarea" v-model="inputChapter" label="分会" ref="分会" outlined rows="1"
          placeholder="Input text here..." />
      </div>

      <div class="q-mb-md extended-input">
        <q-input class="extended-input" type="textarea" v-model="inputName" label="姓名" ref="姓名" outlined rows="1"
          placeholder="Input text here..." />
      </div>
      <div class="q-mb-md extended-input">
        <q-input class="extended-input" type="textarea" @focus="onFocus('inputData1')" @blur="onInput"
          v-model="inputData1" label="行业名称" ref="bussiness" outlined rows="1" placeholder="Input text here..." />
      </div>
      <div class="q-mb-md extended-input">
        <q-input class="extended-input" type="textarea" @focus="onFocus('inputData2')" @blur="onInput"
          v-model="inputData2" label="目标客户(Top3)" ref="top3" outlined rows="3" placeholder="Input text here..." />
      </div>
      <div class="q-mb-md extended-input">
        <q-text>共同目标市场&合作多年&分会空缺行业<br />
          （加入BNI粘性更高生意更多!）</q-text>
        <q-input class="extended-input" type="textarea" @focus="onFocus('inputData3')" @blur="onInput"
          v-model="inputData3" label="共同目标市场&合作多年&分会空缺行业" ref="coopresources" outlined rows="3"
          placeholder="Input text here..." />
      </div>
      <div class="q-mb-md extended-input">
        <q-text>共同目标市场&分会已有行业<br />
          （使用BNI杠杆效益*引荐伙伴）</q-text>
        <q-input class="extended-input" type="textarea" @focus="onFocus('inputData4')" @blur="onInput"
          v-model="inputData4" label="共同目标市场&分会已有行业" ref="alreadyin" outlined rows="3"
          placeholder="Input text here..." />
      </div>
      <div class="q-mb-md extended-input">
        <q-text>共同目标市场&分会空缺行业<br />
          （请为我们邀约嘉宾）</q-text>
        <q-input class="extended-input" type="textarea" @focus="onFocus('inputData5')" @blur="onInput"
          v-model="inputData5" label="共同目标市场&分会空缺行业" ref="notin" outlined rows="3" placeholder="Input text here..." />
      </div>
      <!-- 添加按钮 -->
      <div class="flex justify-start q-mb-md">
        <q-btn label="保存" color="positive" @click="saveInputs" class="q-mr-md" />
        <q-btn label="本地备份" color="info" @click="loadPreviousInputs" />
        <!-- 新添加的按钮 -->
      </div>
      <div class="flex justify-start q-mb-md">
        <q-btn v-show="!isPublic" label="远程提交" color="positive" @click="remoteSubmit" class="q-mr-md" />
        <q-btn v-show="!isPublic" label="远程读取" color="info" @click="remoteFetch" class="q-mr-md" />
      </div>
      <div class="flex justify-start q-mb-md">
        <q-btn label="清空" color="negative" @click="confirmClear" class="q-mr-md" />
        <q-btn label="表格导出" v-show="!isPublic" color="info" @click="exportData" class="q-mr-md" />
        <!-- <q-btn label="会员报告" color="info" @click="goToMemberReport" class="q-mr-md" /> -->
      </div>

      <div class="flex justify-start q-mb-md">
        <q-btn label="登出" color="negative" @click="logout" class="q-mr-md" />
      </div>
    </div>

    <!-- 中间区域 -->
    <div class="echarts-container">
      <div class="flex column items-center q-pa-md" style="width: 100%; height: 100vh">
        <!-- <div class="chart-container" ref="main-sunburst"></div> -->
        <div class="chart-container" ref="main-net"></div>
        <!-- <div class="chart-container" ref="word-cloud"></div> -->
      </div>
    </div>
    <!-- 右边区域 -->

    <div class="scrollable-tree">
      <div class="flex column items-start q-pa-md" style="width: 100%">
        <q-input v-model="searchText" outlined placeholder="Search..." class="q-mb-md" />

        <div v-for="node in topLevelNodesFromFilteredData" :key="node.id">
          <q-item clickable @click="onClickText(node)">
            <q-item-section>{{ node.text }}</q-item-section>
          </q-item>
          <div v-for="childNode in childNodesFor(node, filteredTreeData)" :key="childNode.id" class="q-ml-md">
            <q-item clickable @click="onClickText(childNode)">
              <q-item-section>{{ childNode.text }}</q-item-section>
            </q-item>
            <div v-for="grandchildNode in childNodesFor(
              childNode,
              filteredTreeData
            )" :key="grandchildNode.id" class="q-ml-xl">
              <q-item clickable @click="onClickText(grandchildNode)">
                <q-item-section>{{ grandchildNode.text }}</q-item-section>
              </q-item>
            </div>
          </div>
        </div>
      </div>
    </div>

  </q-page>
</template>

<style>
.chart-container {
  height: 100vh;
  width: 100%;
  margin-bottom: 20px;
}

.extended-input {
  width: 100%;
}

.scrollable-tree {
  width: 20%;
  max-height: 100vh;
  /* 设置最大高度为视窗高度，确保不超出屏幕 */
  overflow-y: auto;
  /* 当内容超出元素高度时，添加垂直滚动条 */
}

.echarts-container {
  width: 50%;
  height: 100vh;
  display: flex;
  /* 使用Flexbox布局 */
  justify-content: center;
  /* 主轴居中对齐 */
  align-items: center;
  /* 交叉轴居中对齐 */
  overflow: hidden;
  /* 防止任何溢出内容被显示 */
}
</style>

<script>
import * as echarts from "echarts";
import "echarts-wordcloud";
import { nextTick, ref } from "vue";
import { save, loadByName, exportToExcel, getMembers } from "src/js/api";
import { StoreModel } from "../js/model";

const baseSymbolSize = 80;

// 计算节点大小的函数
function calculateSymbolSize(name, rate) {
  // 假设你的基本节点大小为10

  // 假设每4个字符增加10%的大小
  const increasePerFourChars = !rate ? 0.2 : rate;
  const numberOfFourCharGroups = Math.ceil(name.length / 8);

  // 计算最终的节点大小
  return baseSymbolSize * (1 + numberOfFourCharGroups * increasePerFourChars);
}

// 计算节点名称，插入换行符的函数
function wrapNodeName(name, maxCharsPerLine) {
  let wrappedName = "";
  for (let i = 0; i < name.length; i += maxCharsPerLine) {
    wrappedName += name.substring(i, i + maxCharsPerLine);
    if (i + maxCharsPerLine < name.length) {
      wrappedName += "\n"; // 插入换行符
    }
  }
  return wrappedName;
}

export default {
  name: "InputContent",

  components: {},
  setup() {
    return {
      inputName: ref(""),
      inputChapter: ref(""),
      inputData1: ref(""),
      inputData2: ref(""),
      inputData3: ref(""),
      inputData4: ref(""),
      inputData5: ref(""),
    };
  },

  data() {
    return {
      showPasswordDialog: false,
      password: '',
      correctPassword: 'yes', // 设置正确的密码
      colors: {
        "top3": "#FF6F61",
        "coopresources": "#FF6F61",
        "alreadyin": "#6B5B95",
        "notin": "#88B04B"//"#FFD700",
      },

      sunburstChart: {},
      netChart: {},
      searchText: "",
      currentInput: {},

      // inputData: "",
      inputLabels: [
        "bussiness",
        "top3",
        "coopresources",
        "alreadyin",
        "notin",
      ],

      isPublic: false,

      treeData: [],
    };
  },

  computed: {
    filteredTreeData() {
      if (!this.searchText) return this.treeData;

      let result = [];

      this.treeData.forEach((node) => {
        if (node.text.includes(this.searchText)) {
          result.push(node);

          // 获取该节点的所有祖先节点
          // let ancestors = this.getAncestors(node);
          // result = result.concat(ancestors);
        }
      });

      // 使用 Set 来去重，确保结果中每个节点只出现一次
      return [...new Set(result)];
    },
    topLevelNodes() {
      return this.treeData;
    },
    topLevelNodesFromFilteredData() {
      // return this.filteredTreeData;
      return this.treeData;
    },
  },

  methods: {

    goToRelations() {
      this.$router.push("/relations");
    },
    async remoteFetch() {
      // 发起POST请求，读取数据

      let res = await loadByName({ uname: this.inputName, inputChapter: this.inputChapter });

      console.log(res);

      let data = res.data.data;
      if (data) {
        this.inputData1 = data.val1;
        this.inputData2 = data.val2;
        this.inputData3 = data.val3;
        this.inputData4 = data.val4;
        this.inputData5 = data.val5;

        this.onInput();
        this.saveToLocal();

      }

    },

    async remoteSubmit() {

      let res = await save({
        uname: this.inputName,
        chapter: this.inputChapter,
        val1: this.inputData1,
        val2: this.inputData2,
        val3: this.inputData3,
        val4: this.inputData4,
        val5: this.inputData5,
      });

      console.log(res);
      this.saveToLocal()
    },

    saveToLocal() {
      let name = this.inputName.trim()
      localStorage.setItem("user-" + name, JSON.stringify({
        "chapter": this.inputChapter,
        "名称": name,
        "行业": this.inputData1,
        "TOP3客户": this.inputData2,
        "拥有的资源": this.inputData3,
        "分会有关行业": this.inputData4,
        "共同客户未进分会": this.inputData5
      }));
    },

    confirmClear() {
      if (confirm("确定要清空所有输入框吗？")) {
        // 清空所有输入框
        this.inputName = "";
        this.inputData1 = "";
        this.inputData2 = "";
        this.inputData3 = "";
        this.inputData4 = "";
        this.inputData5 = "";
      }
    },
    async exportData() {
      let res = await exportToExcel(this.inputChapter)
      console.log(res);
      StoreModel["TableReport"] = res;
      StoreModel["chapter"] = this.inputChapter;
      this.$router.push("TableReport");
      return res;
    },
    saveInputs() {
      if (!this.inputName || !this.inputChapter) {
        return;
      }
      const inputs = {
        inputName: this.inputName,
        inputChapter: this.inputChapter,
        inputData1: this.inputData1,
        inputData2: this.inputData2,
        inputData3: this.inputData3,
        inputData4: this.inputData4,
        inputData5: this.inputData5,
      };
      StoreModel["chapter"] = this.inputChapter;

      localStorage.setItem(this.inputChapter + this.inputName, JSON.stringify(inputs));
      this.saveToLocal()

    },
    loadPreviousInputs() {
      const savedInputs = localStorage.getItem(this.inputChapter + this.inputName);
      if (savedInputs) {
        const parsedInputs = JSON.parse(savedInputs);
        this.inputData1 = parsedInputs.inputData1 || "";
        this.inputData2 = parsedInputs.inputData2 || "";
        this.inputData3 = parsedInputs.inputData3 || "";
        this.inputData4 = parsedInputs.inputData4 || "";
        this.inputData5 = parsedInputs.inputData5 || "";
      }
    },

    getAncestors(node) {
      let ancestors = [];
      let currentparent_id = node.parent_id;

      while (currentparent_id) {
        let parentNode = this.treeData.find(
          (item) => item.id === currentparent_id
        );
        if (parentNode) {
          ancestors.push(parentNode);
          currentparent_id = parentNode.parent_id;
        } else {
          break;
        }
      }

      return ancestors;
    },
    onClickText(leaf) {
      // Handle the event here
      console.log("Clicked on:", leaf.text);
      this.addWord(leaf.text);
    },

    childNodesFor(parentNode, nodes = this.treeData) {
      return nodes.filter((node) => node.parent_id === parentNode.id);
    },

    generateNetData(root) {
      let symbolSize = 80 * 2;
      let nodes = [
        {
          name: root.name,
          symbolSize: calculateSymbolSize(root.name, 0.3),
        },
      ];
      let links = [];

      root.children.forEach((child, idx) => {
        symbolSize = calculateSymbolSize(child.name);

        child.children.forEach((subchild) => {
          nodes.push({
            name: wrapNodeName(subchild.name, 4),
            symbolSize: calculateSymbolSize(subchild.name),
            // itemStyle: { color: this.colors[idx] },
            itemStyle: { color: child.itemStyle.color },
          });
          links.push({
            source: root.name,
            target: wrapNodeName(subchild.name, 4),
            lineStyle: { color: child.itemStyle.color },
          });
        });
      });

      return { nodes, links };
    },
    generateData() {
      let map = {};
      let root = {
        name: `${this.inputName}\n[${this.inputData1}]\n ${this.inputData2 &&
          this.inputData2
            .replace(/，/g, ",")
            .replace(/、/g, ",")
            .split(",")
            .join("\n")
          }`,
        itemStyle: {
          symbolSize: 300,
        },
        children: [],
      };

      map[root.name] = 1;

      let ids = this.inputLabels;
      ids.forEach((id, idx) => {
        let idxmap = {
          bussiness: this.inputData1,
          // top3: this.inputData2,
          coopresources: this.inputData3,
          "alreadyin": this.inputData4,
          notin: this.inputData5,
        };
        let value = idxmap[id];
        // let ref = id;

        if (idx < 2) {
          return;
        }

        if (!value) {
          return;
        }

        let nodeColor = this.colors[id];


        // 加入idx，用于颜色数组的索引
        let input = value.replace(/，/g, ",").replace(/、/g, ",").split(",");
        if (input.length && input[0]) {
          //排除重复值的报错
          input = input.filter((item) => {
            if (!!map[item]) {
              return false;
            } else {
              map[item] = 1;
              return item;
            }
          });

          root.children.push({
            name: id,
            itemStyle: {
              color: nodeColor, // 指定二级数据的颜色
            },
            children: input.map((item) => {
              return {
                name: item,
                value: 1,
                itemStyle: {
                  color: nodeColor, // 指定三级数据的颜色
                },
              };
            }),
          });
        }
      });

      return [root];
    },

    removeDuplicate(el) {
      let list = el.replace(/，/g, ",").replace(/、/g, ",").split(",");
      let mapping = {};
      let result = [];
      list.forEach((item) => {
        if (!mapping[item]) {
          mapping[item] = 1;
          result.push(item);
        }
      });

      return result.join(",");
    },
    addWord(word) {
      console.log(word);
      // 将词条设置为输入框的值
      if (!this[this.currentInput]) {
        this[this.currentInput] += word;
      } else {
        this[this.currentInput] += "," + word;
      }
      // this.currentInput = this.removeDuplicate(this.currentInput);
    },
    onFocus(sel, event) {
      // 在这里编写你的onFocus逻辑
      // console.log('Textarea focused:', event.target.id);
      console.log(sel);
      this.currentInput = sel;
    },
    loadData() {
      let data = localStorage.getItem(this.inputData1);
      let arr = JSON.parse(data);
      arr.forEach((item, index) => {
        let idx = index + 1;
        this["inputData" + idx] = item;
      });
    },
    saveData() {
      localStorage.setItem(
        this.inputData1,
        JSON.stringify([
          this.inputData1,
          this.inputData2,
          this.inputData3,
          this.inputData4,
          this.inputData5,
        ])
      );
    },

    goToMemberReport() {
      this.$router.push("/member-report"); // 跳转到会员报告页面
    },

    logout() {
      // 清除用户数据
      localStorage.removeItem("user");
      // 重定向到登录页面
      this.$router.replace("/login");
    },

    async updateMembers() {
      let result = await getMembers({ chapter: this.inputChapter });
      let list = result.data.data.data;
      console.log("=====", list);
      let data = list.map((item, idx) => {
        return {
          id: idx,
          text: `${item.val1}`,
        };
      }).sort()

      this.treeData = data;
    },
    onInput(newValue) {
      let sunburstData = this.generateData();
      let netData = this.generateNetData(sunburstData[0]);

      // console.log(sunburstData, netData);

      setTimeout(() => {
        try {
          // this.saveData();
          this.netChart.setOption({
            animation: false,
            animationDuration: 0,
            animationDurationUpdate: 0,
            animationThreshold: 0,
            legend: {
              data: ["类型1", "类型2", "类型3"], // 这里的内容应与你的series中的名称相匹配
              // 可以添加其他legend配置，如位置、方向等
            },
            series: [
              {
                animation: false,
                type: "graph",
                layout: "force",
                data: netData.nodes,
                links: netData.links,
                radius: ["30%", "80%"],
                roam: true,
                label: {
                  position: "inside",
                  formatter: "{b}",
                  show: true,
                  fontSize: 20,
                },
                force: {
                  layoutAnimation: false,
                  repulsion: 1000,
                  edgeLength: [100, 150],
                },
              },
            ],
          });
        } catch (error) {
          console.error(error);
        }
      }, 100);
    },
  },

  async mounted() {
    // 检查用户是否登录
    let userData = localStorage.getItem("user")
    if (!userData) {
      this.$router.replace("/login") // 修改为你的登录页面路由
      return;
    }


    this.showPasswordDialog = true;
    let uesrdata = localStorage.getItem("user")
    // if(!uesrdata){
    //   this.$router.replace("LoginPage")
    //   return;
    // }
    let user = JSON.parse(uesrdata) || {}
    this.inputName = user.uname || "";
    this.inputChapter = user.Chapter || "天河永丰";

    // this.sunburstChart = echarts.init(this.$refs["main-sunburst"]);
    this.netChart = echarts.init(this.$refs["main-net"]);

    this.onInput();

    this.updateMembers();

    this.remoteFetch();

    // 设置定时器保存输入信息
    // this.interval = setInterval(this.saveInputs, 2000);
  },

};
</script>
